

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="风间">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. 基本概念 通常情况下，集合中可以存放不同类型的对象，是因为将所有对象当做 Object 类型放入的，因此从集合中取出元素时也是 Object 类型，为了表达该元素真实的数据类型，则需要强制类型转换，而强制类型转换可能会引发类型转换异常。 12345678910111213List lt1 &#x3D; new LinkedList();lt1.add(&quot;jack&quot;);lt1.add">
<meta property="og:type" content="article">
<meta property="og:title" content="Java 泛型">
<meta property="og:url" content="http://example.com/2023/05/08/%E5%90%8E%E7%AB%AF/java/Java%E6%B3%9B%E5%9E%8B/index.html">
<meta property="og:site_name" content="风间小栈">
<meta property="og:description" content="1. 基本概念 通常情况下，集合中可以存放不同类型的对象，是因为将所有对象当做 Object 类型放入的，因此从集合中取出元素时也是 Object 类型，为了表达该元素真实的数据类型，则需要强制类型转换，而强制类型转换可能会引发类型转换异常。 12345678910111213List lt1 &#x3D; new LinkedList();lt1.add(&quot;jack&quot;);lt1.add">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s3.bmp.ovh/imgs/2023/04/27/5db2a22dcf8946ea.png">
<meta property="article:published_time" content="2023-05-08T01:46:03.860Z">
<meta property="article:modified_time" content="2023-05-08T01:46:03.860Z">
<meta property="article:author" content="风间">
<meta property="article:tag" content="泛型">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://s3.bmp.ovh/imgs/2023/04/27/5db2a22dcf8946ea.png">
  
  
  <title>Java 泛型 - 风间小栈</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.13","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"§"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>风间小栈</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/%E6%96%87%E6%9C%AC.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Java 泛型">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2023-05-08 09:46" pubdate>
        2023年5月8日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.9k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      33 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Java 泛型</h1>
            
            <div class="markdown-body">
              <h2 id="1-基本概念"><a href="#1-基本概念" class="headerlink" title="1. 基本概念"></a>1. 基本概念</h2><ul>
<li><p>通常情况下，集合中可以存放不同类型的对象，是因为将所有对象当做 Object 类型放入的，因此从集合中取出元素时也是 Object 类型，为了表达该元素真实的数据类型，则需要强制类型转换，而强制类型转换可能会引发类型转换异常。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java">List lt1 = <span class="hljs-keyword">new</span> LinkedList();<br><br>lt1.add(<span class="hljs-string">&quot;jack&quot;</span>);<br>lt1.add(<span class="hljs-number">123</span>);<br>lt1.add(<span class="hljs-keyword">true</span>);<br><br><span class="hljs-keyword">for</span> (Object o : lt1) &#123;<br>    String s1 = (String) o;<br>    System.out.println(s1);<br>&#125;<br><br>异常提醒：<br>java.lang.Integer cannot be cast to java.lang.String<br></code></pre></td></tr></table></figure></li>
<li><p>为了避免上述错误的发生，从 Java5 开始增加泛型机制，也就是在集合名称的右侧使用<code>&lt;数据类型&gt;</code>的方式来明确要求该集合中可以存放的元素类型，若放入其它类型的元素则编译报错。</p>
</li>
<li><p>泛型只在编译期有效，在运行时期不区分是什么类型。</p>
</li>
</ul>
<h2 id="2-底层原理"><a href="#2-底层原理" class="headerlink" title="2. 底层原理"></a>2. 底层原理</h2><ul>
<li><p>泛型的本质就是<code>参数化类型</code>，也就是让数据类型作为参数传递，其中 E 相当于形式参数负责占位，而使用集合时<code>&lt;&gt;</code>中的数据类型相当于实际参数，用于给形式参数 E 进行初始化，从而使得集合中所有的 E 被实际参数替换，由于实际参数可以传递各种各样广泛的数据类型，因此得名为泛型。</p>
<p>如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 其中 i 叫做形式参数，负责占位</span><br><span class="hljs-comment">// int i = 10;</span><br><span class="hljs-comment">// int i = 20;</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">show</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span></span>&#123;<br>    ...<br>&#125;<br><span class="hljs-comment">// 其中 10 叫做实际参数，负责给形式参数初始化</span><br>show(<span class="hljs-number">10</span>);<br>show(<span class="hljs-number">20</span>);<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 其中 E 叫做形式参数，负责占位</span><br><span class="hljs-comment">// E = String;</span><br><span class="hljs-comment">// E = Integer;</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">List</span>&lt;<span class="hljs-title">E</span>&gt;</span>&#123;<br>    ...<br>&#125;<br><span class="hljs-comment">// 其中 String 叫做实际参数</span><br>List&lt;String&gt; lt1 = ...;<br>List&lt;Integer&gt; lt2 = ...;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="3-自定义泛型接口"><a href="#3-自定义泛型接口" class="headerlink" title="3. 自定义泛型接口"></a>3. 自定义泛型接口</h2><p>泛型接口和普通接口的区别就是后面添加了类型参数列表，可以有多个类型参数，如：&lt;E,T…&gt;等。</p>
<h2 id="4-自定义泛型类"><a href="#4-自定义泛型类" class="headerlink" title="4. 自定义泛型类"></a>4. 自定义泛型类</h2><ul>
<li><p>泛型类型和普通类型的区别就是类名后面添加了类型参数列表，可以有多个类型参数，如&lt;E,T…&gt;等。</p>
</li>
<li><p>实例化泛型类时应该指定具体的数据类型，并且是引用数据类型，而不是基本数据类型</p>
<p>自定义泛型类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br><br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;<br>    <span class="hljs-keyword">private</span> T gender;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">()</span> </span>&#123;<br><br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age, T gender)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.name = name;<br>        <span class="hljs-keyword">this</span>.age = age;<br>        <span class="hljs-keyword">this</span>.gender = gender;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> name;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.name = name;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> age;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.age = age;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">getGender</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> gender;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setGender</span><span class="hljs-params">(T gender)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.gender = gender;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Person&#123;&quot;</span> +<br>                <span class="hljs-string">&quot;name=&#x27;&quot;</span> + name + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +<br>                <span class="hljs-string">&quot;, age=&quot;</span> + age +<br>                <span class="hljs-string">&quot;, gender=&quot;</span> + gender +<br>                <span class="hljs-string">&#x27;&#125;&#x27;</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>使用泛型类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 限制类型，gender 被限制为 String 类型</span><br>Person&lt;String&gt; p1 = <span class="hljs-keyword">new</span> Person&lt;&gt;(<span class="hljs-string">&quot;jack&quot;</span>, <span class="hljs-number">18</span>, <span class="hljs-string">&quot;男&quot;</span>);<br>System.out.println(p1);<br><br><span class="hljs-comment">// 未限制类型的使用，gender 仍被当做 Object 类型</span><br>Person p2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">&quot;jack&quot;</span>, <span class="hljs-number">18</span>, <span class="hljs-string">&quot;男&quot;</span>);<br>System.out.println(p2);<br></code></pre></td></tr></table></figure></li>
<li><p>父类有泛型，子类可以选择保留泛型，也可以指定泛型类型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 不保留父类的泛型</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SubPerson</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span></span>&#123;<br>    ...<br>&#125;<br><br><span class="hljs-comment">// 指定父类泛型类型</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SubPerson</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span>&lt;<span class="hljs-title">String</span>&gt;</span>&#123;<br>    ...<br>&#125;<br><br><span class="hljs-comment">// 保留父类泛型</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SubPerson</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span>&lt;<span class="hljs-title">T</span>&gt;</span>&#123;<br>    ...<br>&#125;<br><br></code></pre></td></tr></table></figure></li>
<li><p>子类除了保留和指定父类的泛型外，还可以增加自己的泛型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 保留父类泛型的同时，新增自己的泛型</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SubPerson</span>&lt;<span class="hljs-title">T</span>,<span class="hljs-title">K</span>&gt; <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span>&lt;<span class="hljs-title">T</span>&gt;</span>&#123;<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="5-自定义泛型方法"><a href="#5-自定义泛型方法" class="headerlink" title="5. 自定义泛型方法"></a>5. 自定义泛型方法</h2><ul>
<li><p>泛型方法就是我们输入参数的时候，输入的是泛型参数，而不是具体类型的参数。我们在调用这个泛型方法的时候需要对泛型参数进行示例化。</p>
</li>
<li><p>泛型方法的格式：</p>
<p>[访问权限] &lt;泛型&gt; 返回值类型 方法名([泛型标识符 参数名称]){方法体;}</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> &lt;T&gt; <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printName</span><span class="hljs-params">(T t)</span></span>&#123;<br>    ...<br>&#125;<br><br><span class="hljs-keyword">public</span> &lt;T&gt; <span class="hljs-function">String <span class="hljs-title">printName</span><span class="hljs-params">(T t)</span></span>&#123;<br>    ...<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;xxx&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>在静态方法中使用泛型参数的时候，需要我们把静态方法定义成泛型方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;T&gt; <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printName</span><span class="hljs-params">(T t)</span></span>&#123;<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="6-泛型在继承上的体现"><a href="#6-泛型在继承上的体现" class="headerlink" title="6. 泛型在继承上的体现"></a>6. 泛型在继承上的体现</h2><ul>
<li><p>如果 B 是 A 的一个子类或接口，而 G 是具有泛型声明的类或接口，则 G<B> 并不是 G<A> 的子类型！</p>
<p>比如：String 是 Object 的子类，但 List<String> 并不是 List<Object> 的子类。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java">List&lt;String&gt; lt1 = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();<br><br>List&lt;Object&gt; lt2 = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();<br><br>lt2 = lt1; <span class="hljs-comment">// 错误 ×</span><br><br><br>String s1 = <span class="hljs-string">&quot;abc&quot;</span>;<br><br>Object s2 = <span class="hljs-string">&quot;1234&quot;</span>;<br>       <br>s2 = s1;<span class="hljs-comment">// 正确 √</span><br></code></pre></td></tr></table></figure></li>
<li><p>需要使用通配符来确定父子类型</p>
<ul>
<li>List&lt;?&gt; 是 List&lt;? extends Number&gt; 的父类型</li>
<li>List&lt;? extends Number&gt; 是 List&lt; Integer &gt; 的父类型</li>
</ul>
</li>
</ul>
<h2 id="7-通配符的使用"><a href="#7-通配符的使用" class="headerlink" title="7. 通配符的使用"></a>7. 通配符的使用</h2><ul>
<li><p>有时候我们希望传入的类型在一个指定的范围内，此时就可以使用泛型通配符了。</p>
<p>如：之前传入的类型要求为 Integer 类型，但是后来业务需要 Integer 的父类 Number 类也可以传入</p>
</li>
<li><p>泛型通配符有三种形式：（限定存入的类型，根据父类引用指向子类对象，通常当做方法参数使用）</p>
<ul>
<li><?> 无限制通配符：表示我们可以传入任意类型

不支持添加元素，因为可以存放任意类型，如果允许添加，则编译器无法知道即将放入的到底是什么类型，可能会出现类型强转异常

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">List&lt;?&gt; lt5 = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();<br><br>lt5.add(<span class="hljs-string">&quot;jack&quot;</span>);<span class="hljs-comment">// 错误 ×，</span><br>lt5.get(<span class="hljs-number">0</span>);<span class="hljs-comment">// 正确 √</span><br></code></pre></td></tr></table></figure></li>
<li><? extends E> 表示类型的上界是 E，只能是 E 或者 E 的子类

不支持添加元素，因为允许的类型是 E 或 E的子类，父类引用可以指向子类，子类不可以指向父类，所以这里面不确定放入的是哪个子类，也可能会出现类型强转异常

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">List&lt;? extends Person&gt; lt6 = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();<br>lt6.add(<span class="hljs-keyword">new</span> Person());<span class="hljs-comment">// 错误 ×，这里的 ? 如果是代表 SubPerson</span><br>lt6.add(<span class="hljs-keyword">new</span> SubPerson());<span class="hljs-comment">// 错误 ×，这里的 ? 如果是 SubPerson 的子类</span><br>lt6.get(<span class="hljs-number">0</span>);<span class="hljs-comment">// 正确 √</span><br></code></pre></td></tr></table></figure></li>
<li><? super E> 表示类型的下界是 E，只能是 E 或 E 的父类
支持添加元素，这里存入的是 E 或 E 的父类，最小就是 E，那么凡事可以用 E 指向的类型都可以存放（还是父类引用指向子类对象）

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java">List&lt;? <span class="hljs-keyword">super</span> Person&gt; lt7 = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();<br>lt7.add(<span class="hljs-keyword">new</span> Person());<span class="hljs-comment">// 正确 √，这里的 ? 是 Person 或 Person 父类</span><br>lt7.add(<span class="hljs-keyword">new</span> SubPerson());<span class="hljs-comment">// 正确 √，这里的 ? 是 Person 或 Person 父类</span><br></code></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%90%8E%E7%AB%AF/">后端</a>
                    
                      <a class="hover-with-bg" href="/categories/%E5%90%8E%E7%AB%AF/java/">java</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E6%B3%9B%E5%9E%8B/">泛型</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/05/08/%E5%90%8E%E7%AB%AF/java/jdk%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">JDK 动态代理</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/05/08/%E5%90%8E%E7%AB%AF/java/ElasticSearch/">
                        <span class="hidden-mobile">分布式搜索引擎-ElasticSearch</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="SOHUCS" sid='http://example.com/2023/05/08/%E5%90%8E%E7%AB%AF/java/Java%E6%B3%9B%E5%9E%8B/'></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#SOHUCS', function() {
      Fluid.utils.createScript("https://changyan.sohu.com/upload/changyan.js", function() {
        window.changyan.api.config({"appid":"cywjv2D9l","appkey":"2bf2f1231299e92b26393ba6fb2ad9d8"})
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    风间小栈出品
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
